<template>
  <el-dialog
    :title="
      controlDeviceInfo.deviceParentName +
        '/' +
        controlDeviceInfo.name +
        '-任务列表'
    "
    :append-to-body="true"
    :visible="visible"
    width="80%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="close"
  >
    <div>
      <el-row :gutter="10">
        <el-form ref="form" :model="searchForm" label-width="auto" size="small">
          <el-col :span="5" :offset="0">
            <el-form-item label="零件号">
              <el-input v-model="searchForm.partNumber" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="5" :offset="0">
            <el-form-item label="批次号">
              <el-input v-model="searchForm.batchNumber" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="5" :offset="0">
            <el-form-item label="工序号">
              <el-input
                v-model="searchForm.processNumber"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="5" :offset="0">
            <el-form-item label="工序名称">
              <el-input
                v-model="searchForm.name1"
                placeholder="请输入"
              ></el-input> </el-form-item
          ></el-col> -->
          <el-col :span="4" :offset="0">
            <el-button size="small" type="primary" @click="onSearchSubmit"
              >搜索</el-button
            >
            <el-button size="small" @click="handleReset">重置</el-button>
          </el-col>
        </el-form>
      </el-row>
      <el-table :data="tableData" size="small" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-table
              v-if="scope.row.childrenList.length"
              :data="scope.row.childrenList"
              border
              size="mini"
            >
              <el-table-column type="index" label="序号" />
              <el-table-column
                prop="taskchildnumber"
                label="子任务号"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  {{ scope.row.taskchildnumber }}
                </template>
              </el-table-column>
              <el-table-column
                prop="partNumber"
                show-overflow-tooltip
                label="零件号"
              >
                <template slot-scope="scope">
                  {{ scope.row.partNumber }}
                </template>
              </el-table-column>
              <el-table-column
                prop="batchNumber"
                show-overflow-tooltip
                label="批次号"
              >
                <template slot-scope="scope">
                  {{ scope.row.batchNumber }}
                </template>
              </el-table-column>
              <el-table-column
                prop="processNumber"
                show-overflow-tooltip
                label="工序/工步号"
              >
                <template slot-scope="scope">
                  {{ scope.row.processNumber }}
                </template></el-table-column
              >
              <el-table-column
                prop="processName"
                show-overflow-tooltip
                label="工序/工步名称"
                width="120"
              >
                <template slot-scope="scope">
                  {{ scope.row.processName }}
                </template>
              </el-table-column>
              <el-table-column
                prop="partTotalCount"
                show-overflow-tooltip
                label="数量"
                ><template slot-scope="scope">
                  {{ scope.row.partTotalCount }}
                </template>
              </el-table-column>
              <el-table-column
                prop="materialMark"
                show-overflow-tooltip
                label="材料牌号"
                ><template slot-scope="scope">
                  {{ scope.row.materialMark }}
                </template>
              </el-table-column>
              <el-table-column
                prop="craftVersion"
                show-overflow-tooltip
                label="工艺版次"
                ><template slot-scope="scope">
                  {{ scope.row.craftVersion }}
                </template>
              </el-table-column>
            </el-table>
            <!-- 预热炉部分只有一个设定温度 -->
            <el-table
              style="margin-top: 10px"
              :data="scope.row.formulaDownloadInfo"
              border
              size="mini"
            >
              <el-table-column
                prop="stageId"
                show-overflow-tooltip
                label="阶段号"
                align="center"
                ><template slot-scope="downscope">
                  {{ downscope.row.stageId || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="setTemp"
                label="设定温度℃"
                align="center"
                show-overflow-tooltip
                ><template slot-scope="downscope">
                  {{ downscope.row.setTemp || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="setTime"
                show-overflow-tooltip
                align="center"
                label="设定时间min"
                ><template slot-scope="downscope">
                  {{ downscope.row.setTime || "-" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="volumeTemp"
                align="center"
                show-overflow-tooltip
                label="温度公差℃"
                ><template slot-scope="downscope">
                  {{ downscope.row.volumeTemp || "-" }}
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          type="index"
          width="50"
          label="序号"
          align="center"
        />
        <el-table-column
          show-overflow-tooltip
          prop="taskNumber"
          label="任务号"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.taskNumber }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="partName"
          label="状态"
          align="center"
        >
          <template slot-scope="scope">
            {{
              scope.row.taskStatus !== ""
                ? TASK_STATUS[Number(scope.row.taskStatus)]
                : "-"
            }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="lastOutTime"
          label="时间"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.createdDate | formatDate }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="partNumber"
          label="零件号"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.partName }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="batchNumber"
          label="批次号"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.batchNumber }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="processNumber"
          label="工序/工步号"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.processNumber }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="processName"
          label="工序/工步名称"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.processName }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="partTotalCount"
          label="数量"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.partTotalCount }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="materialMark"
          label="材料牌号"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.materialMark }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="craftVersion"
          label="工艺版次"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.craftVersion }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template slot-scope="scope">
            <i
              class="el-icon-edit"
              style="font-size: 18px; margin-right: 10px; color: #409eff"
              @click="editStage(scope.row)"
            />
            <i
              class="el-icon-bottom"
              style="font-size: 18px; color: #409eff"
              @click="handleIssued(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span slot="footer">
      <el-button size="small" @click="close"> 取 消</el-button>
    </span>
    <!-- 阶段编辑 -->
    <StageComs
      :stage-btnloading="stageBtnloading"
      :formula-parameter="stageTable"
      :stage-visible.sync="stageVisible"
      :form="{
        formulaParameter: stageTable
      }"
      :is-issued="isIssued"
      @submit="submit"
    />
    <!-- 阶段下发(包含工艺的) -->
    <IssuedStage
      :stageVisible.sync="issuedStageVisible"
      :stage-btnloading="stageBtnloading"
      :formula-parameter="issStageTable"
      :form="issTableData"
      :is-issued="isIssued"
      @submit="submit2"
    ></IssuedStage>
  </el-dialog>
</template>

<script>
import {
  updateFormulaDownloadInfo,
  getTaskDownLoadInfos,
  formulaEdit
} from "@/api/deviceOperation";
import { useTable, TASK_STATUS } from "../../js/utils";
import StageComs from "./Stage.vue";
import IssuedStage from "./IssuedStage.vue";
import _ from "lodash";
import { mapGetters } from "vuex";
import { formulaRules } from "@/views/centralizedControl/deviceOperation/constant";
export default {
  components: { StageComs, IssuedStage },
  props: {
    visible: {
      type: Boolean,
      default: false
    },

    manufactureSite: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      issuedStageVisible: false,
      isIssued: false,
      TASK_STATUS,
      stageVisible: false,
      tableData: [],
      searchForm: {
        partNumber: "",
        batchNumber: "",
        processNumber: ""
      },
      rules: {},
      form: {},
      row: {},
      stageTable: [],
      issStageTable: [],
      issTableData: {
        tableData: []
      },
      stageBtnloading: false
    };
  },
  computed: {
    ...mapGetters(["controlDeviceInfo"]),
    deviceToken() {
      return this.controlDeviceInfo.token;
    }
  },
  watch: {
    //  //
    //  //阶段
    // deviceToken: {
    //   handler: function (newData, oldData) {
    //     console.info("任务下发是否存在token", newData);
    //     if (newData) {
    //       this.getTaskDownLoadInfos();
    //     }
    //   },
    //   immediate: true,
    // },
  },
  mounted() {
    // 获取任务下发弹框列表
  },
  methods: {
    // 阶段提交
    async submitStage() {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await formulaEdit([this.row.id]);
          this.stageBtnloading = false;
          const { data } = res;
          console.log("data :>> ", data);
          if (data) {
            this.$msg({
              type: "success",
              message: "下发成功"
            });
            resolve();
          } else {
            this.$msg("下发失败");
            reject();
          }
        } catch (error) {
          this.$msg(error);
          this.stageBtnloading = false;
          reject();
        }
      });
    },
    // 编辑阶段
    submitInfo(stageTable = this.stageTable) {
      return new Promise((resolve, reject) => {
        updateFormulaDownloadInfo(
          this.row.token,
          stageTable.map((item, index) => {
            return {
              ...item,
              stageId: index + 1,
              token: "",
              formulaDownid: this.row.formulaDownid,
              volumeTemp: 10
            };
          })
        ).then(res => {
          resolve();
        });
      });
    },
    // 下发的
    async submit2() {
      if (!this.issStageTable.length) {
        this.$msg("当前没有配方可下发");
        return;
      }
      this.stageBtnloading = true;
      await this.submitInfo(
        this.issTableData.tableData.map(item => {
          return {
            setTime: item.setTime,
            setTemp: item.setTemp,
            volumeTemp: item.volumeTemp
          };
        })
      );
      await this.submitStage();
      this.stageBtnloading = false;
      this.issuedStageVisible = false;
      this.getTaskDownLoadInfos();
    },
    // 编辑阶段/下发提交
    async submit() {
      if (!this.stageTable.length) {
        this.$msg("请添加阶段信息");
        return;
      }
      this.stageBtnloading = true;
      await this.submitInfo();
      // 下发
      await this.submitStage();
      this.stageBtnloading = false;
      this.stageVisible = false;
      this.getTaskDownLoadInfos();
    },
    async editStage(row) {
      this.isIssued = false;
      // const s = row.formulaDownloadInfo.stageId.length;
      this.stageTable = _.cloneDeep(row.formulaDownloadInfo);
      this.row = _.cloneDeep(row);
      this.stageVisible = true;
      // const res = await formulaRecordDetails(row.token);
    },
    // 下发
    handleIssued(row) {
      this.issuedStageVisible = true;
      if (!row.formulaParameter.length) {
        this.$msg("当前任务不存在工艺配方");
        return;
      }
      const arr = _.cloneDeep(row.formulaParameter);
      // 取出表头
      this.issStageTable = [];
      this.issTableData = {
        tableData: []
      };
      arr[0].keys.forEach((key, keyIndex) => {
        this.issStageTable.push({
          label: key,
          key: key
        });
      });
      this.$set(
        this.issTableData,
        "tableData",
        arr.map(item => {
          let obj = {};
          item.keys.forEach((key, keyIndex) => {
            obj[key] = item.values[keyIndex];
          });
          // formulaRules.UP_TIME
          let setTime = "";
          //保温时间 一样直接赋值
          if (obj[formulaRules.UP_TIME] == obj[formulaRules.DOW_TIME]) {
            setTime = obj[formulaRules.UP_TIME];
          }
          // 热透时间上限 一样直接赋值
          if (
            obj[formulaRules.UP_HEAT_TIME] == obj[formulaRules.DOW_HEAT_TIME]
          ) {
            setTime = obj[formulaRules.UP_HEAT_TIME];
          }

          return {
            ...obj,
            setTime: setTime,
            setTemp:
              obj[formulaRules.UP_TEMP] == obj[formulaRules.DOW_TEMP]
                ? obj[formulaRules.UP_TEMP]
                : "",
            volumeTemp: 10
          };
        })
      );

      this.row = _.cloneDeep(row);
    },
    // 任务列表
    async getTaskDownLoadInfos() {
      const res = await getTaskDownLoadInfos({
        parentTaskNumber: "ROOT",
        deviceToken: this.deviceToken,
        ...this.searchForm,
        taskStatus: 0
      });
      const { results } = res.data;
      // this.tableData = results;
      this.tableData = results;

      console.log("任务列表 :>> ", this.tableData);
    },
    handleReset() {
      Object.assign(this.$data.searchForm, this.$options.data().searchForm);
      this.getTaskDownLoadInfos();
    },
    // 搜索
    onSearchSubmit() {
      this.getTaskDownLoadInfos();
    },
    close() {
      this.$emit("update:visible", false);
    }
  }
};
</script>

<style></style>
